import './App.css';
import React from 'react';
import { Button, Toast, WhiteSpace, Tabs, List, NavBar, Icon, WingBlank, Checkbox, Flex, Accordion, Modal, Result, Badge } from 'antd-mobile';
import moment from 'moment';
import { createForm } from 'rc-form';
import * as request from './request';
import Toolbar from "./Toolbar";

const Item = List.Item;
const apiURL = "/api/services/app/Edu_Children/Get?id=";
const apiURL2 = "/api/services/app/Edu_Children/";
const apiQuestURL = "/api/services/app/Edu_QuestionBank/GetList?skipCount=0&maxResultCount=10";
const apiQuestDtlURL = "/api/services/app/Edu_QuestionDtl/GetListWithAnsw?bankId=";

const myImg = src => <img src={src} className="spe am-icon am-icon-md" alt="" />;
const playerCrt = function (vodid) {
    return "//1301299150.vod2.myqcloud.com/vod-player/1301299150/" + vodid + "/tcplayer/console/vod-player.html?autoplay=false&width=1280&height=720";
}
const myBadge = function (val) {
    return <Badge text={val} style={{ backgroundColor: '#00BCD4', borderRadius: 2, cursor: 'pointer', marginBottom: 4, marginLeft: 4 }} />
}
var qIds = [];
const isHas = function (qId) {
    let indexC = qIds.indexOf(qId);
    if (indexC < 0) {
        qIds.push(qId);
    }
    return indexC;
}
const scoreNote = function (score) {
    if (score >= 100) {
        return "优秀";
    }
    else if (score > 90) {
        return "良好";
    }
    else if (score > 80) {
        return "中等";
    }
    else if (score >= 60) {
        return "合格";
    }
    else {
        return "需努力";
    }
}
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            babyData: {
                name: '',
                correctAge: 0
            },
            dataSource: [],
            dataDtl: [],
            open: false,
            title: '儿童评测',
            score: 0,
            modal1: false,
            initialPage: 0,
            abilityCognitive: 0,
            abilityFineMotion: 0,
            abilityGreatAth: 0,
            abilityLang: 0,
            abilitySocial: 0
        }
    }
    componentDidMount() {
        this.fetchData();
    }
    fetchData = () => {
        var cid = this.props.match.params.childid;
        if (!cid) {
            cid = localStorage.getItem('childid');
        }
        if (cid) {
            Toast.loading('Loading...', 0);
            request.get(apiURL + cid)
                .then((data) => {
                    let babyData = data.result;
                    let _this = this
                    this.setState({ babyData }, function () {
                        _this.fetchQuestData();
                    })
                    this.setState({ abilityCognitive: babyData.abilityCognitive ? babyData.abilityCognitive : 0 })
                    this.setState({ abilityFineMotion: babyData.abilityFineMotion ? babyData.abilityFineMotion : 0 })
                    this.setState({ abilityGreatAth: babyData.abilityGreatAth ? babyData.abilityGreatAth : 0 })
                    this.setState({ abilityLang: babyData.abilityLang ? babyData.abilityLang : 0 })
                    this.setState({ abilitySocial: babyData.abilitySocial ? babyData.abilitySocial : 0 })
                    Toast.hide();
                })
                .catch((error) => {
                    console.log('fetch data failed', error);
                });
        }
    }

    fetchQuestData = () => {
        const { babyData } = this.state;
        let m = babyData.correctAge;
        request.get(apiQuestURL + '&babyAge=' + m)
            .then((data) => {
                this.setState({ dataSource: data.result.items })
            })
            .catch((error) => {
                console.log('fetch data failed', error);
            });
    }

    fetchQuestDtlData = () => {
        const { bankId } = this.state;
        Toast.loading('Loading...', 1);
        request.get(apiQuestDtlURL + bankId)
            .then((data) => {
                this.setState({ dataDtl: data.result.items })
            })
            .catch((error) => {
                Toast.fail('fetch data failed!' + error, 1);
            });
    }

    onOpenChange = (...args) => {
        this.setState({ open: !this.state.open });
    }
    showDtl = (...args) => {
        this.setState({ open: !this.state.open, initialPage: 1 });
        if (args) {
            let _this = this;
            let obj = args[0];
            let testType = 'abilityGreatAth';
            this.setState({ bankId: obj.id, title: obj.title, testType }, function () {
                _this.fetchQuestDtlData();
            })
        }
    }
    submit = () => {
        // this.props.form.validateFields((error, value) => {
        //     console.log(value);
        // });
        const { title, score } = this.state;
        if (title.indexOf('语言') >= 0) {
            this.setState({ abilityLang: score })
        }
        else if (title.indexOf('社交') >= 0) {
            this.setState({ abilitySocial: score })
        }
        else if (title.indexOf('精细运动') >= 0) {
            this.setState({ abilityFineMotion: score })
        }
        else if (title.indexOf('认知') >= 0) {
            this.setState({ abilityCognitive: score })
        }
        else {
            this.setState({ abilityGreatAth: score })
        }
        this.setState({ modal1: true })
    }
    submit2 = () => {
        const { babyData, abilityCognitive, abilityFineMotion, abilityGreatAth, abilityLang, abilitySocial } = this.state;
        let value = {
            id: babyData.id,
            abilityCognitive,
            abilityFineMotion,
            abilityGreatAth,
            abilityLang,
            abilitySocial
        }
        request.put(apiURL2 + 'UpdateAbility', value).then((response) => {
            if (response) {
                if (response.success) {
                    Toast.success('提交成功！');
                    this.props.history.push('/BabyRadar')
                }
                else {
                    Toast.fail(response.error.message);
                }
                this.setState({ loading: false });
            }
        });
    }
    onChange = (e, record, qType, qId) => {
        const { score } = this.state;
        // if(qType==='单选题' && isHas(qId)>=0)
        // {
        //     e.target.checked=false;
        //     console.log(isHas(qId));
        // }
        var fen = score;
        if (e.target.checked) {
            fen += record.points;
        }
        else {
            fen -= record.points;
        }
        this.setState({ score: fen })
    }
    render() {
        const { dataSource, dataDtl, title, babyData, initialPage } = this.state;
        const { getFieldProps, getFieldError } = this.props.form;
        const tabs = [
            { title: '题库' },
            { title: '题目' },
        ];
        const sidebar = (<List>
            {dataSource.map((i, index) => {
                return (<List.Item
                    arrow="horizontal"
                    multipleLine
                    platform="android"
                    key={index}
                    onClick={() => this.showDtl(i)}
                >
                    {index + 1}、{i.title}<List.Item.Brief>编号{i.bankNum}，适合 {i.age} ~ {i.ageMax} 个月大{i.sex === '1' ? '男' : '女'}宝宝</List.Item.Brief>
                </List.Item>)
            })}
        </List>);
        const AnswerItem = (dataSource, props, qType, qId) => {
            const { getFieldProps, getFieldError } = props.form;
            return (<List>

                {dataSource.map((i, index) => {
                    return (<List.Item
                        key={index}>
                        <Checkbox.CheckboxItem onChange={(e) => this.onChange(e, i, qType, qId)} name='answers' value={i.points}>{i.ansContent}</Checkbox.CheckboxItem>
                        {/* <Radio className="my-radio" onChange={(e) => this.onChange(e, i, qType, qId)}  value={i.points}>{i.ansContent}</Radio> */}
                    </List.Item>)
                })}
            </List>
            );
        }
        const imgList = (items) => {
            var dataSource = items.split(',')
            return (
                <div>
                    {dataSource.map((i, index) => {
                        return (
                            <a onClick={() => { this.setState({ modal3: true, imageUrl: i }); }}><img src={request.imgServer + i} style={{width:50,height:50,marginRight:5}} /></a>
                        )
                    })}

                </div>
            )
        }
        const age = request.getAge(moment(babyData.birthday).format("YYYY-MM-DD"));

        return (
            <div>
                <NavBar
                    mode="light"
                    icon={<Icon type="left" />}
                    onLeftClick={() => this.props.history.push('/BabyRadar')}
                    rightContent={[
                        <Icon key="1" type="ellipsis" onClick={this.onOpenChange} />,
                    ]}
                    style={{ width: '100%' }}>{title}</NavBar>
                <WhiteSpace size="md" />
                <WingBlank size="md">
                    <Accordion className="my-accordion">
                        <Accordion.Panel header={babyData.name + ' ' + babyData.correctAge + '个月'}>
                            <List className="my-list">
                                <Item extra={babyData.name}>宝宝姓名</Item>
                                <Item extra={moment(babyData.birthday).format("YYYY-MM-DD")}>出生日期</Item>
                                <Item extra={babyData.sex}>宝宝性别</Item>
                                <Item extra={babyData.weight + ' kg'}>宝宝体重</Item>
                                <Item extra={babyData.gweek + '周'}>宝宝胎龄</Item>
                                <Item extra={(babyData.gweek < 40 ? babyData.correctGestionalAge : babyData.correctAge) + (babyData.gweek < 40 ? "周" : "月")}>{babyData.gweek < 40 ? "纠正胎龄" : "纠正月龄"}</Item>

                            </List>
                        </Accordion.Panel>
                    </Accordion>
                    <Tabs tabs={tabs}
                        initialPage={initialPage}
                        page={initialPage}
                        swipeable={false}
                        onChange={(tab, index) => this.setState({ initialPage: index })}
                    >
                        <div key='0'>
                            {sidebar}
                            <WhiteSpace size="lg" />
                            <WhiteSpace size="lg" />
                            <WhiteSpace size="lg" />
                        </div>
                        <div key='1'>
                            <form>
                                <List>
                                    {dataDtl.map((i, index) => {
                                        return (<List.Item
                                            multipleLine
                                            platform="android"
                                            key={index}
                                            wrap
                                        >
                                            {i.questionNum}、{i.title}<List.Item.Brief>
                                                {i.contents}
                                                {i.imageUrl ? imgList(i.imageUrl) : null}
                                                {i.videoUrl ? <a onClick={() => { this.setState({ modal2: true, videoUrl: i.videoUrl }); }}>{myBadge('示范视频')}</a> : null}
                                            </List.Item.Brief>
                                            {AnswerItem(i.items, this.props, i.qType, i.id)}
                                        </List.Item>)
                                    })}
                                </List>
                            </form>
                            <WhiteSpace size="md" />
                            <Button type="primary" onClick={this.submit} disabled={dataDtl.length <= 0} >提交</Button>
                            <WhiteSpace size="md" />
                            <div style={{ textAlign: 'center' }}>—— 全部做完，请点击 ↓ ——</div>
                            <WhiteSpace size="md" />
                            <Button type="warning" onClick={this.submit2} style={{ marginBottom: 100 }}>完成提交</Button>
                        </div>
                    </Tabs>

                </WingBlank>
                <Modal
                    visible={this.state.modal1}
                    transparent
                    maskClosable={false}
                    onClose={() => this.setState({ modal1: false })}
                    title="评测结果"
                    footer={[{ text: 'Ok', onPress: () => { this.setState({ modal1: false }); } }]}
                    wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                >
                    <Result
                        img={<Icon type="check-circle" style={{ fill: '#1F90E6', width: 60, height: 60 }} />}
                        title={"" + this.state.score + "分"}
                        message={title + scoreNote(this.state.score)}
                    />
                </Modal>

                <Modal
                    visible={this.state.modal2}
                    transparent
                    maskClosable={false}
                    onClose={() => this.setState({ modal2: false })}
                    title="示例视频"
                    footer={[{ text: 'Ok', onPress: () => { this.setState({ modal2: false }); } }]}
                    wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                >
                    <iframe src={playerCrt(this.state.videoUrl)} frameBorder="0" scrolling="no" width="100%" allowFullScreen >
                    </iframe>
                </Modal>
                <Modal
                    visible={this.state.modal3}
                    transparent
                    maskClosable={false}
                    onClose={() => this.setState({ modal2: false })}
                    title="示例图"
                    footer={[{ text: 'Ok', onPress: () => { this.setState({ modal3: false }); } }]}
                    wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                >
                    <img src={request.imgServer + this.state.imageUrl} width="100%" />
                </Modal>

                <Toolbar history={this.props.history} selectedTab='BabyTest' />
            </div>
        )
    };
}

export default createForm()(App);
